<template>
    <Modal v-model="visible" :title="title" @on-ok="ok" :mask-closable="false">
        <Tree ref="tree" :data="authorities" show-checkbox></Tree>

        <div slot="footer">
            <Button type="text" size="large" @click.native="cancel">取消</Button>
            <Button type="primary" size="large" :loading="loading" @click.native="ok">确定</Button>
        </div>
    </Modal>
</template>
<script>
    import api from '../../api';

    export default {
        props: ['getData'],
        data () {
            return {
                visible: false,
                loading: false,
                title: '',
                authorities: [],
                roleId: ''
            };
        },
        methods: {
            ok () {
                const checkedNodes = this.$refs.tree.getCheckedNodes();
                const roleAuthorityList = checkedNodes.map(item => {
                    return {authorityId: item.id};
                });
                const params = {
                    id: this.roleId,
                    roleAuthorityList: roleAuthorityList
                };
                api.roleUpdateAuthority(params).then(data => {
                    if (data.code === 0) {
                        this.getData();
                        this.visible = false;
                    }
                });
            },
            open (title, id) {
                this.visible = true;
                this.title = title;
                this.roleId = id;

                if (id) {
                    api.authorityTree({roleId: id}).then(data => {
                        if (data.code === 0) {
                            this.authorities = data.data;
                        }
                    });
                }
            },
            cancel () {
                this.visible = false;
            }
        }
    };
</script>
